#include "mystdio.h"
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>

MYFILE* myfopen(const char* name,const char* mode)
{
    int fd = -1;
    //不同打开方式打开文件
    if(strcmp(mode,"w")==0)
    {
        fd = open(name,O_CREAT | O_WRONLY | O_TRUNC,UMASK);
    }
    else if(strcmp(mode,"r")==0)
    {
        fd = open(name,O_RDONLY);
    }
    else if(strcmp(mode,"a")==0)
    {
        fd = open(name,O_CREAT | O_WRONLY | O_APPEND,UMASK);
    }
    else if(strcmp(mode,"a+")==0)
    {
        fd = open(name,O_CREAT | O_RDWR | O_APPEND,UMASK);
    }
    else 
    {
        //...
    }
    if(fd < 0)
    {
        return NULL;
    }

    MYFILE* fp = (MYFILE*)malloc(sizeof(MYFILE));
    if(fp == NULL)
    {
        return NULL;
    }
    
    fp->fileno = fd;
    fp->flag = FLUSH_LINE;
    fp->cur = 0;
    fp->cap = SIZE;
    fp->outbuffer[0]=0;

    return fp;

}

static void my_fflush_core(MYFILE* fp,int f)
{
    if(fp->cur<0)
    {
        return;
    }
    if(f == FORCE)//强制刷新
    {
        write(fp->fileno,fp->outbuffer,fp->cur);
        fp->cur=0;
        return;
    }
    else 
    {
        if((fp->flag & FLUSH_LINE)&&(fp->outbuffer[fp->cur-1]=='\n'))
        {
            write(fp->fileno,fp->outbuffer,fp->cur);
            fp->cur=0;
            return;
        }
        else if((fp->flag & FLUSH_FULL)&&(fp->cur==fp->cap))
        {
            write(fp->fileno,fp->outbuffer,fp->cur);
            fp->cur=0;
            return;
        }
        else 
        {
            //....
        }
    }
}

int mywrite(const char* s,int size,MYFILE* fp)
{
    //fwrite的本质是拷贝
    memcpy(fp->outbuffer + fp->cur, s ,size);
    fp->cur += size;
    my_fflush_core(fp,NORMAL);
    return size;
}
void myfclose(MYFILE* fp)
{
    if(fp->fileno>0)
    {
        myfflush(fp);//用户-->C
        fsync(fp->fileno);//C-->内核
        close(fp->fileno);
        free(fp);
    }
}
void myfflush(MYFILE* fp)
{
    my_fflush_core(fp,NORMAL);
}
